<template>
  <el-dialog
    :title="title"
    append-to-body
    :visible.sync="upsertRoleDialogVisible"
    :close-on-click-modal="false"
    width="500px"
    @close="close"
  >
    <el-form ref="form" size="small" :model="formValue" :rules="formRules">
      <el-form-item label="角色名" prop="roleName">
        <el-input v-model="formValue.roleName" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input
          v-model="formValue.roleDesc"
          placeholder="功能权限："
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="flex justify-center">
      <el-button class="w-20" round @click="close">取消</el-button>
      <el-button class="w-20" round type="primary" @click="upsertRoleConfirm"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script lang="ts">
import Vue from 'vue'
import { ActionsType } from '@/actions/system'
import { treeData } from '@/pages/admin/system/rights.data.ts'
export default Vue.extend({
  data() {
    return {
      upsertRoleDialogVisible: false,
      flag: 'add', // update
      formValue: {
        id: '',
        roleName: '',
        roleDesc: '',
      },
      formRules: {
        roleName: [
          {
            required: true,
            message: '请填写角色名',
          },
        ],
      },
    }
  },
  computed: {
    title() {
      return this.flag === 'add' ? '新建角色' : '修改角色'
    },
  },
  mounted() {},
  methods: {
    show(item: Record<string, any>) {
      if (item) {
        this.formValue.id = item.id
        this.formValue.roleName = item.roleName
        this.formValue.roleDesc = item.roleDesc
        this.flag = 'update'
      } else {
        this.flag = 'add'
      }
      this.upsertRoleDialogVisible = true
    },
    close() {
      this.upsertRoleDialogVisible = false
      this.$refs.form?.resetFields()
      this.$emit('close')
    },
    async upsertRoleConfirm() {
      // this.$refs.form.resetField()
      try {
        await this.$refs.form?.validate()
        const params = {
          roleName: this.formValue.roleName,
          roleDesc: this.formValue.roleDesc,
        }
        if (this.flag === 'update') {
          params.id = this.formValue.id
        } else {
          params.menuList = treeData
          params.dataPermission = 'Owner'
        }
        await this.$store.dispatch(ActionsType.upsertRole, params)
        this.close()
        this.$message.success(`${this.title}成功!`)
      } catch (error) {
        console.error(error)
      }
    },
  },
})
</script>

<style></style>
